package com.twu.biblioteca.service;

import com.twu.biblioteca.Library;
import com.twu.biblioteca.exception.InvalidCheckReturnException;
import com.twu.biblioteca.model.Book;

import java.util.ArrayList;
import java.util.List;

import static com.twu.biblioteca.model.Status.available;
import static com.twu.biblioteca.model.Status.lended;
import static com.twu.biblioteca.util.Messages.*;

public class BookService {
    public static List<String> bookMenu = new ArrayList<String>();
    private Library library;
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void setLibrary(Library library) {
        this.library = library;
    }

    public Book checkoutBook(int bookId, String accountId) throws InvalidCheckReturnException {
        Boolean flag = userService.checkLogin(accountId);
        if (flag) {
            Book book = library.findBook(bookId);
            if (book != null && book.getStatus().equals(available)) {
                library.markBookStatus(book, lended);
                return book;
            } else {
                throw new InvalidCheckReturnException(THAT_BOOK_IS_NOT_AVAILABLE);
            }
        } else {
            throw new InvalidCheckReturnException(PLEASE_LOGIN_FIRST_YOU_CAN_INPUT_COMMAND_LOGIN_TO_LOGIN_THE_SYSTEM);
        }
    }

    public Book returnBook(int bookId, String accountId) throws InvalidCheckReturnException {
        boolean flag = userService.checkLogin(accountId);
        if (flag) {

            Book book = library.findBook(bookId);
            if (book != null && book.getStatus().equals(lended)) {
                library.markBookStatus(book, available);
                return book;
            } else {
                throw new InvalidCheckReturnException(THAT_IS_NOT_A_VALID_BOOK_TO_RETURN);
            }
        } else {
            throw new InvalidCheckReturnException(PLEASE_LOGIN_FIRST_YOU_CAN_INPUT_COMMAND_LOGIN_TO_LOGIN_THE_SYSTEM);
        }
    }

    public List<Book> getAllBooks() {

        return library.getBooks();
    }
}
